package org.jeecg.common.util.pay.wx;

import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.Transaction;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;

import static com.wechat.pay.java.core.http.Constant.*;

/**
 * @Description:
 * @Author: Planifolia.Van
 * @Date: 2025/1/9 10:38
 */
@Component
@Slf4j
public class WxPayNotifyParser {

    private final NotificationParser notificationParser;

    /**
     * 构造器注入初始化回调解析器
     *
     * @param wxPayConfig 微信支付配置
     */
    @Autowired
    public WxPayNotifyParser(Config wxPayConfig) {
        // 初始化 NotificationParser 回调通知解析器
        this.notificationParser = new NotificationParser((NotificationConfig) wxPayConfig);
    }

    /**
     * 微信回调处理器
     *
     * @param request 请求
     * @return 若解析正确会获取到订单号
     */
    public Result<?> wxNotifyHandler(HttpServletRequest request) {
        try {
            //读取请求体的信息
            ServletInputStream inputStream = request.getInputStream();
            StringBuilder stringBuffer = new StringBuilder();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String s;
            //读取回调请求体
            while ((s = bufferedReader.readLine()) != null) {
                stringBuffer.append(s);
            }
            String s1 = stringBuffer.toString();
            log.info("回调信息:{}", s1);
            String timestamp = request.getHeader(WECHAT_PAY_TIMESTAMP);
            String nonce = request.getHeader(WECHAT_PAY_NONCE);
            String signType = request.getHeader("Wechatpay-Signature-Type");
            String serialNo = request.getHeader(WECHAT_PAY_SERIAL);
            String signature = request.getHeader(WECHAT_PAY_SIGNATURE);

            RequestParam requestParam = new RequestParam.Builder()
                    .serialNumber(serialNo)
                    .nonce(nonce)
                    .signature(signature)
                    .timestamp(timestamp)
                    .signType(signType)
                    .body(s1)
                    .build();
            Transaction parse = notificationParser.parse(requestParam, Transaction.class);
            if (Transaction.TradeStateEnum.SUCCESS.equals(parse.getTradeState())) {
                //你的业务代码
                String outTradeNo = parse.getOutTradeNo();
                return Result.OK("解析成功！", outTradeNo);
            } else {
                return Result.error("解析失败！");
            }
        } catch (Exception e) {
            throw new JeecgBootException(e);
        }
    }
}
